package at.ptasat.util;

import java.io.IOException;
import java.io.OutputStream;

public final class SequenceInsertingOutputStream extends OutputStream {
	private final OutputStream out;
	private final byte[] postfix;
	private final byte[] sequence;
	private int position;
	
	public SequenceInsertingOutputStream(OutputStream out, byte[] postfix, byte[] sequence) {
		if (out == null || postfix == null || sequence == null) {
			throw new NullPointerException();
		}
		if (postfix.length == 0) {
			throw new IllegalArgumentException("Length of prefix must be greater than zero!");
		}
		this.out = out;
		this.postfix = postfix.clone();
		this.sequence = sequence.clone();
		position = 0;
	}
	
	@Override
	public void write(final int value4) throws IOException {
		final byte value = (byte) value4;
		if(postfix[position] == value) {
			position++;
			if(position == postfix.length){
				out.write(sequence);
				out.write(postfix);
				position = 0;
			}
		} else {
			out.write(postfix, 0, position);
			out.write(value);
		}
	}

	@Override
	public void flush() throws IOException {
		out.write(postfix, 0, position);
		out.flush();
	}

	@Override
	public void close() throws IOException {
		flush();
		out.close();
	}

	/*
	 * private final OutputStream out; private final byte[] prefix; private
	 * final byte[] sequence; private final boolean[] positions;
	 * 
	 * public SequenceInsertingOutputStream(OutputStream out, byte[] prefix,
	 * byte[] sequence) { if (out == null || prefix == null || sequence == null)
	 * { throw new NullPointerException(); } if (prefix.length == 0) { throw new
	 * IllegalArgumentException("Length of prefix must be greater than zero!");
	 * } this.out = out; this.prefix = prefix.clone(); this.sequence =
	 * sequence.clone(); positions = new boolean[prefix.length]; positions[0] =
	 * true; }
	 * 
	 * @Override public void write(final int value4) throws IOException {
	 * out.write(value4); final byte value = (byte) value4; boolean prefixFound
	 * = false; for (int i = 0; i < prefix.length; i++) { if (positions[i] &&
	 * value == prefix[i]) { positions[i] = false; if (i + 1 < prefix.length) {
	 * positions[i + 1] = true; } else { prefixFound |= true; } if (i == 0) {
	 * positions[0] = true; } } } if (prefixFound) { out.write(sequence); } }
	 * 
	 * @Override public void flush() throws IOException { out.flush(); }
	 * 
	 * @Override public void close() throws IOException { out.close(); }
	 */
}
